package com.cloudcc.mobile.view.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.RequestListener;
import com.cloudcc.cloudframe.net.ResultCallBack;
import com.cloudcc.cloudframe.ui.viewgroup.LazyViewPager;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.ReceiverConstant;
import com.cloudcc.mobile.adapter.BeauRelationAdapter;
import com.cloudcc.mobile.adapter.DynamicAdapter;
import com.cloudcc.mobile.adapter.RelevantChatAdatper;
import com.cloudcc.mobile.adapter.RelevantPopAdapter;
import com.cloudcc.mobile.dao.impl.ChatterEngineImpl;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.beau.BeauInfoEntity;
import com.cloudcc.mobile.entity.beau.BeauInfoEntity.ObjMenu;
import com.cloudcc.mobile.entity.beau.BeauInfoEntity.ObjRelation;
import com.cloudcc.mobile.entity.beau.BeauInfoEntity.TabLabel;
import com.cloudcc.mobile.entity.chatter.ChatterEventType;
import com.cloudcc.mobile.event.BeauEventList.BeauInfoEvent;
import com.cloudcc.mobile.event.BeauEventList.DynamicListEvent;
import com.cloudcc.mobile.event.refresh.RefreshEntiityListEvent;
import com.cloudcc.mobile.manager.CacheManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.network.QianDaoNewWork;
import com.cloudcc.mobile.presenter.BeauPresenter;
import com.cloudcc.mobile.presenter.OtherPresenter;
import com.cloudcc.mobile.util.PopuWindowUtils;
import com.cloudcc.mobile.util.SystemUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.ViewUtils;
import com.cloudcc.mobile.view.activity.BeauLitterListActivity;
import com.cloudcc.mobile.view.activity.CreateMultipleListActivity;
import com.cloudcc.mobile.view.activity.EditorActivity;
import com.cloudcc.mobile.view.activity.ShowBaiduMapActivity;
import com.cloudcc.mobile.view.activity.TaskManagementHistoryActivty;
import com.cloudcc.mobile.view.base.BaseFragment;
import com.cloudcc.mobile.view.base.BaseWebViewFragment;
import com.cloudcc.mobile.view.dynamic.dynamic.DynamicFragment;
import com.cloudcc.mobile.view.market.MarketActivityInfoActivity;
import com.cloudcc.mobile.view.web.CloudWebViewActivity;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy.MonitorParam;
import com.cloudcc.mobile.weight.EmptyLayout;
import com.cloudcc.mobile.widget.CloudCCTitleBar;
import com.cloudcc.mobile.widget.CloudCCTitleBar.OnTitleBarClickListener;
import com.google.gson.JsonObject;

/**
 * @Description: TODO()
 * @author wangzhiqiang
 * @date 2015-11-19 下午4:00:53
 * 
 */
public class BeauInfoFragment extends BaseFragment implements IEventLife,
		OnCheckedChangeListener, OnTitleBarClickListener {

	private Map<String, String[]> mEntityTypes;

	@Bind(R.id.beau_name)
	TextView beau_name;
	@Bind(R.id.beau_name_sub)
	TextView beau_name_sub;
	@Bind(R.id.beau_location)
	ImageView beau_location;
	@Bind(R.id.beau_call)
	ImageView beau_call;
	@Bind(R.id.beau_email)
	ImageView beau_email;

	@Bind(R.id.beau_dynamic)
	TextView beau_dynamic;
	@Bind(R.id.beau_detail)
	TextView beau_detail;

	ListView mListView;
	@Bind(R.id.container)
	LinearLayout mContainer;

	@Bind(R.id.beau_information)
	LinearLayout beau_information;

	@Bind(R.id.relevent_dibu)
	RelativeLayout relevent_dibu;

	@Bind(R.id.context_text)
	EditText context_text;

	@Bind(R.id.headerbar)
	CloudCCTitleBar headerbar;

	@Bind(R.id.radiogroup)
	RadioGroup radiogroup;

	@Bind(R.id.viewpager)
	LazyViewPager mViewPager;

	@Bind(R.id.rv1)
	RecyclerView mRe;

	private BeauPresenter mBeauPresenter = new BeauPresenter();

	private BeauInfoEntity mBeauInfo;

	private DynamicFragment mDynamicFragment;
	private MyDetailWeb mDetailFragment;

	@Override
	public void init() {
		initHeader();
		initEntityMap();
		initRelationView();
		register();
		refreshInfoData();
		initContainer();
		registerDynamicRefreshReceiver();// 注册刷新监听
		radiogroup.setOnCheckedChangeListener(this);
		initViewPager();
		initReceiver();
		initChatterEventTypes();
	}

	/**
	 * 初始化横向列表
	 */
	private void initRelationView() {
		// 设置布局
		LinearLayoutManager layoutManager = new LinearLayoutManager(
				getActivity(), LinearLayoutManager.HORIZONTAL, false);
		mRe.setLayoutManager(layoutManager);
	}

	private void initEntityMap() {
		mEntityTypes = new HashMap<String, String[]>();
		// Contact Opportunity Lead Account
		String[] contactKeys = mContext.getResources().getStringArray(
				R.array.entity_type_contact);
		String[] opportunityKeys = mContext.getResources().getStringArray(
				R.array.entity_type_opportunity);
		String[] leadKeys = mContext.getResources().getStringArray(
				R.array.entity_type_lead);
		String[] accountKeys = mContext.getResources().getStringArray(
				R.array.entity_type_account);
		String[] otherKeys = mContext.getResources().getStringArray(
				R.array.entity_type_other);
		mEntityTypes.put("contact", contactKeys);
		mEntityTypes.put("opportunity", opportunityKeys);
		mEntityTypes.put("lead", leadKeys);
		mEntityTypes.put("account", accountKeys);
		mEntityTypes.put("other", otherKeys);
	}

	/**
	 * 初始化标题
	 */
	private void initHeader() {
		title = getArguments().getString("beau.name", "");
		// beau.edit
		boolean isEditFouse = getArguments().getBoolean("beau.edit", false);
		if (isEditFouse) {
			context_text.requestFocus();
		}
		mEntityId = getArguments().getString("beau.id", "");
		mEntityNameID = getArguments().getString("beau.nameid", "");
		isMeFollow = getArguments().getBoolean("beau.ismefollow", false);
		headerbar.setTitle(title);
		headerbar.setOnTitleBarClickListener(this);
	}

	/**
	 * 初始化 viewpager
	 */
	private void initViewPager() {
		mDynamicFragment = new MyDynamicFragment();
		mDetailFragment = new MyDetailWeb();
		// 赋值
		mDynamicFragment.requestData();
		ArrayList<Fragment> views = new ArrayList<Fragment>();
		views.add(mDynamicFragment);
		views.add(mDetailFragment);

		RelevantChatAdatper viewPagerAdapter = new RelevantChatAdatper(
				getActivity().getSupportFragmentManager(), views);
		mViewPager.setAdapter(viewPagerAdapter);

	}

	private MyReceiver mDynamicRefreshReceiver;

	private void registerDynamicRefreshReceiver() {
		mDynamicRefreshReceiver = new MyReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(AppContext.INDEXADAPTER_SHUAXIN);
		filter.addAction(AppContext.RECORD_ID_CHANGED_SHUAXIN);
		mContext.registerReceiver(mDynamicRefreshReceiver, filter);
	}

	private class MyReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(AppContext.INDEXADAPTER_SHUAXIN)
					|| action.equals(AppContext.RECORD_ID_CHANGED_SHUAXIN)) {
				if (mDynamicFragment != null && mDynamicFragment.isResumed()) {
					mDynamicFragment.onRefreshData();
				}
			}
		}
	}

	/**
	 * @Description: 子类
	 * @author wangzhiqiang
	 * @date 2015-12-14 下午8:08:57
	 * 
	 */
	private class MyDynamicFragment extends DynamicFragment {

		private EmptyLayout empty_loading;

		@Override
		public void init() {
			mRefreshLayout.setEnabled(false);
			initLoadMore();
			mListView.setBackgroundColor(Color.parseColor("#57F2F8F8"));
			empty_loading = new EmptyLayout(mContext);
			empty_loading.setLayoutParams(new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
			ViewUtils.addListViewEmptyView(mContext, mListView, empty_loading);
		}

		@Override
		public String getQueryType() {
			return "";
		}

		@Override
		public void requestData() {
			mControl.getDynamicsAboutRecord(currentPage, mEntityId);
		}

		@Override
		public int getLayoutId() {
			return super.getLayoutId();
		}

		public void onEventMainThread(DynamicListEvent event) {
			if ((event.isError() && isFromRefresh())
					|| (ListUtils.isEmpty(event.getData()) && isFromRefresh())) {// 加载数据为空
				empty_loading.empty();
				return;
			}
			if (mAdapter == null) {
				mAdapter = new DynamicAdapter(mContext);
				mListView.setAdapter(mAdapter);
				mListView.setOnItemClickListener(this);
				mAdapter.setOnItemtListener(this);
			}
			if (isFromRefresh()) {
				mAdapter.changeData(event.getData());
			} else {
				mAdapter.addData(event.getData());
			}

		}

		@Override
		protected void onRequestFinish(boolean dataIsEmpty) {
			mLoadMoreLayout.loadMoreFinish(false, true);
		}

		@Override
		protected void initRequestData() {
			// 禁止自动刷新
		}

	}

	private class MyDetailWeb extends BaseWebViewFragment {
		
		public MyDetailWeb() {
			super();
		}

		private EmptyLayout empty_loading;

		@Override
		public void init() {
			empty_loading = (EmptyLayout) findViewById(R.id.emptylayout);
			super.init();
		}

		@Override
		protected void onPreInitWebView() {
			if (StringUtils.equalsIgnoreCase(mEntityNameID, "attachement")) {
				mUrl = UrlManager.getManager().getEntityDetailNoHeaderUrl1(
						mEntityId);
			} else {
				mUrl = UrlManager.getManager().getEntityDetailNoHeaderUrl(
						mEntityId);
			}

		}

		@Override
		protected void startProgressDialog() {
			empty_loading.setVisibility(View.VISIBLE);
		}

		@Override
		protected void stopProgressDialog() {
			empty_loading.setVisibility(View.GONE);
			mWebView.setVisibility(View.VISIBLE);
		}

		@Override
		public int getLayoutId() {
			return R.layout.beau_info_detail;
		}

		public void refreshWeb() {
			try {
				mWebView.setVisibility(View.GONE);
				mWebView.reload();
			} catch (Exception e) {
			}

		}
	}

	private void initContainer() {
	}

	private PopupWindow popupWindow;

	@OnClick(R.id.leixing)
	public void clickLeiXing() {
		showPopu();
	}

	/**
	 * 初始化 事件类型
	 */
	private void initChatterEventTypes() {
		mTypes = CacheManager.getInstance().getEventTypes();
		refreshEventTypes();
	}

	/**
	 * 刷新事件类型了列表
	 */
	private void refreshEventTypes() {
		new ChatterEngineImpl()
				.getChatterEventTypes(new ResultCallBack<List<ChatterEventType>>() {

					@Override
					public void onSuccess(List<ChatterEventType> types) {
						mTypes = types;
						CacheManager.getInstance().cacheEventTypes(types);
					}

					@Override
					public void onFailure(ErrorInfo error) {
						mTypes = CacheManager.getInstance().getEventTypes();
					}
				});
	}

	private List<ChatterEventType> mTypes;

	private List<String> fillEventTypes() {
		List<String> list = new ArrayList<String>();
		if (ListUtils.isEmpty(mTypes)) {
			list.add("汇报记录");
			list.add("发讨论帖");
			list.add("签到拜访");
			list.add("记录电话");
			list.add("记录短信");
			list.add("记录邮件");
			list.add("写个备注");
			return list;
		}
		for (ChatterEventType type : mTypes) {
			if (StringUtils.isBlank(type.key)) {
				continue;
			}
			list.add(type.key);
		}
		return list;
	}

	protected void showPopu() {
		PopuWindowUtils.dissmiss(popupWindow);
		if (ListUtils.isEmpty(mTypes)) {
			Toast.makeText(mContext, "类型不存在。。。", 0).show();
			return;
		}
		View view = LayoutInflater.from(mContext).inflate(
				R.layout.relevant_pop, null);
		ListView listView = (ListView) view.findViewById(R.id.relevant_popup);
		listView.setScrollbarFadingEnabled(true);
		List<String> list = fillEventTypes();
		final RelevantPopAdapter adapter2 = new RelevantPopAdapter(mContext,
				list);
		listView.setAdapter(adapter2);
		popupWindow = new PopupWindow(view,
				AppContext.getInstance().screenW * 2 / 5,
				AppContext.getInstance().screenH / 3);
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(relevent_dibu, 5, 3);
		listView.setOnItemClickListener(new OnItemClickListener() {
			private String relevantName;
			private String key;
			private String reuevantType;

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (popupWindow.isShowing()) {
					popupWindow.dismiss();
				}
				String name = adapter2.getItem(arg2);
				try {
					JsonObject jsonObject = mBeauInfo.recordInformationList
							.get(0);// 详情对象
					relevantName = name + "【"
							+ GsonUtil.getStringByJson("name", jsonObject)
							+ "】";
					AppContext.relevantName = GsonUtil.getStringByJson("name",
							jsonObject);
				} catch (Exception e) {
					relevantName = name;
					e.printStackTrace();
				}
				reuevantType = name;
				key = "1";
				Intent intent = new Intent(mContext, EditorActivity.class);
				intent.putExtra("urlId", mEntityId);
				intent.putExtra("key", key);
				intent.putExtra("CustomerActivity", relevantName);
				intent.putExtra("reuevantType", reuevantType);
				intent.putExtra("name", name);
				intent.putExtra("from", "web");
				startActivity(intent);

			}
		});
	}

	/**
	 * 刷新info 数据
	 */
	private void refreshInfoData() {
		for (Map.Entry<String, String[]> entry : mEntityTypes.entrySet()) {
			if (StringUtils.equalsIgnoreCase(mEntityNameID, entry.getKey())) {
				requestKey = entry.getKey();
			}
		}
		String[] strings = mEntityTypes.get(requestKey);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < strings.length; i++) {
			sb.append(strings[i].trim());
			sb.append(",");
		}
		headerbar.beginProgress();
		mBeauPresenter.getBeauInfo(mEntityId, mEntityNameID, sb.toString()
				.substring(0, sb.length() - 1));
	}

	public void onEventMainThread(BeauInfoEvent event) {
		headerbar.completeProgress();
		if (event.isError()) {
			Toast.makeText(mContext, "亲,获取详情失败~~", 0).show();
			getActivity().finish();
			return;
		}
		mBeauInfo = event.getData();
		fillDetails();
	}

	/**
	 * 填充详情
	 */
	private void fillDetails() {
		if (mBeauInfo == null
				|| ListUtils.isEmpty(mBeauInfo.recordInformationList)) {
			return;
		}

		if (!ListUtils.isEmpty(mBeauInfo.relationList)) {// 开始请求
			fillRelation();
		}
		JsonObject jsonObject = mBeauInfo.recordInformationList.get(0);// 详情对象
		ViewUtils.setText(beau_name,
				GsonUtil.getStringByJson("name", jsonObject));
		List<MapKeyObj> fieldList = new ArrayList<BeauInfoFragment.MapKeyObj>();
		fieldList.clear();

		if (StringUtils.equalsIgnoreCase(mEntityNameID, "contact")) {// 联系人
			fieldList.add(new MapKeyObj("company", ""));
			fieldList.add(new MapKeyObj("zhiwu", ""));
			beau_call.setVisibility(View.VISIBLE);
			beau_email.setVisibility(View.VISIBLE);
			beau_location.setVisibility(View.GONE);

		} else if (StringUtils.equalsIgnoreCase(mEntityNameID, "opportunity")) {
			fieldList.add(new MapKeyObj("jieduan", ""));
			fieldList.add(new MapKeyObj("jsrq", ""));
			fieldList.add(new MapKeyObj("yqsr", ""));
			beau_call.setVisibility(View.INVISIBLE);
			beau_email.setVisibility(View.INVISIBLE);
			beau_location.setVisibility(View.GONE);

		} else if (StringUtils.equalsIgnoreCase(mEntityNameID, "lead")) {
			fieldList.add(new MapKeyObj("company", ""));
			beau_call.setVisibility(View.VISIBLE);
			beau_email.setVisibility(View.VISIBLE);
			beau_location.setVisibility(View.VISIBLE);
		} else if (StringUtils.equalsIgnoreCase(mEntityNameID, "account")) {
			fieldList.add(new MapKeyObj("hangye", ""));
			fieldList.add(new MapKeyObj("leixing", ""));
			beau_call.setVisibility(View.VISIBLE);
			beau_email.setVisibility(View.VISIBLE);
			beau_location.setVisibility(View.VISIBLE);
		} else {
			fieldList.add(new MapKeyObj("owneridccname", ""));
			beau_call.setVisibility(View.INVISIBLE);
			beau_email.setVisibility(View.INVISIBLE);
			beau_location.setVisibility(View.INVISIBLE);
		}
		// 获取数据
		for (MapKeyObj mapKeyObj : fieldList) {
			String stringByJson = GsonUtil.getStringByJson(mapKeyObj.key,
					jsonObject);
			mapKeyObj.value = stringByJson;
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < fieldList.size(); i++) {
			MapKeyObj mapKeyObj = fieldList.get(i);
			String value = mapKeyObj.value;
			if (!TextUtils.isEmpty(value)) {
				sb.append(mapKeyObj.value);
				if (i != fieldList.size() - 1) {
					sb.append(" · ");
				}
			}
		}
		if (!TextUtils.isEmpty(sb.toString())) {
			ViewUtils.setText(beau_name_sub, sb.toString());
		}

	}

	private static class MapKeyObj {
		public String key;
		public String value;

		public MapKeyObj(String key, String value) {
			super();
			this.key = key;
			this.value = value;
		}

	}

	/**
	 * 填充相关列表
	 */
	private void fillRelation() {
		if (mBeauInfo == null || ListUtils.isEmpty(mBeauInfo.relationList)) {
			return;
		}
		mRe.setVisibility(View.VISIBLE);
		BeauRelationAdapter adapter = new BeauRelationAdapter(
				mBeauInfo.relationList, getActivity());
		adapter.setOnItemClickListener(new com.cloudcc.cloudframe.ui.OnItemClickListener() {
			@Override
			public void onItemClick(int position) {
				// 根据不同的判断进入不同的页面
				ObjRelation objRelation = mBeauInfo.relationList.get(position);

				if (StringUtils.equals("bde", objRelation.prefix)) {// 活动历史
					Intent intent = new Intent(mContext,
							BeauLitterListActivity.class);
					intent.putExtra("name", objRelation.relationName);
					intent.putExtra("layoutId", objRelation.layoutId);
					intent.putExtra("recordId", mEntityId);
					intent.putExtra("relatedlistId", objRelation.relatedlistId);
					startActivity(intent);
				} else if (StringUtils.equals("abe", objRelation.prefix)) {// 审批历史
					Intent intent = new Intent(mContext,
							TaskManagementHistoryActivty.class);
					intent.putExtra("relatedId", mEntityId);
					intent.putExtra("title", objRelation.relationName);
					startActivity(intent);
				} else {
					Intent intent = new Intent(mContext,
							CreateMultipleListActivity.class);
					intent.putExtra("name", objRelation.relationName);
					intent.putExtra("layoutId", objRelation.layoutId);
					intent.putExtra("recordId", mEntityId);
					intent.putExtra("relatedlistId", objRelation.relatedlistId);
					intent.putExtra("prefix", objRelation.prefix);
					intent.putExtra("beau.ismefollow", isMeFollow);
					List<ObjMenu> objMenulist = new ArrayList<BeauInfoEntity.ObjMenu>();
					if (mBeauInfo != null) {
						for (int i = 0; i < mBeauInfo.relationCreateUrl.size(); i++) {
							ObjMenu obj = mBeauInfo.relationCreateUrl.get(i);
							if (obj.relatedlistId
									.equals(objRelation.relatedlistId)) {
								objMenulist.add(obj);
							}
						}
					}
					intent.putExtra("objMenulist", (Serializable) objMenulist);
					startActivity(intent);
				}

			}
		});
		mRe.setAdapter(adapter);
	}

	@Override
	public int getLayoutId() {
		return R.layout.beau_info_layout;
	}

	@OnClick(R.id.beau_call)
	public void clickPhone() {
		if (hasBeauInfoData()) {
			Toast.makeText(mContext, "亲，暂无电话~~", 0).show();
			return;
		}
		JsonObject jsonObject = mBeauInfo.recordInformationList.get(0);
		String mobilePhone = GsonUtil.getStringByJson("phone", jsonObject);
		if (StringUtils.isNotBlank(mobilePhone)) {
			SystemUtils.sendCall(mContext, mobilePhone);
		} else {
			Toast.makeText(mContext, "亲，暂无电话~~", 0).show();
		}
	}

	@OnClick(R.id.beau_location)
	public void clickLocation() {
		if (hasBeauInfoData()) {
			Toast.makeText(mContext, "亲，暂无地址~~", 0).show();
			return;
		}
		JsonObject jsonObject = mBeauInfo.recordInformationList.get(0);
		String address = StringUtils.isBlank(GsonUtil.getStringByJson("khdd",
				jsonObject)) ? GsonUtil.getStringByJson("address", jsonObject)
				: GsonUtil.getStringByJson("khdd", jsonObject);
		if (StringUtils.isNotBlank(address)) {
			Intent intent = new Intent(mContext, ShowBaiduMapActivity.class);
			intent.putExtra("address", address);
			startActivity(intent);
		} else {
			Toast.makeText(mContext, "亲，暂无地址~~", 0).show();
		}
	}

	@OnClick(R.id.beau_email)
	public void clickEmail() {
		if (hasBeauInfoData()) {
			Toast.makeText(mContext, "亲，暂无邮件地址~~", 0).show();
			return;
		}
		JsonObject jsonObject = mBeauInfo.recordInformationList.get(0);
		String email = GsonUtil.getStringByJson("email", jsonObject);
		if (StringUtils.isNotBlank(email)) {
			SystemUtils.sendEmail(mContext, email);
		} else {
			Toast.makeText(mContext, "亲，暂无邮件地址~~", 0).show();
		}
	}

	/**
	 * 是不是 有详情
	 * 
	 * @return
	 */
	private boolean hasBeauInfoData() {
		return mBeauInfo == null
				|| ListUtils.isEmpty(mBeauInfo.recordInformationList)
				|| mBeauInfo.recordInformationList.get(0) == null;
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void onDestroy() {
		if (mDynamicRefreshReceiver != null) {
			mContext.unregisterReceiver(mDynamicRefreshReceiver);
		}
		if (mSyncReceiver != null) {
			mContext.unregisterReceiver(mSyncReceiver);
		}
		EventEngine.uregister(this);
		super.onDestroy();
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

	private PopupWindow mRightMenu;
	private String mEntityId;
	private String mEntityNameID;
	private String title;
	private boolean isMeFollow = false;

	@OnClick(R.id.relevant_fasong)
	public void sendRelevantChat() {
		String name = context_text.getText().toString().trim();
		if (name.equals("")) {
			Tools.showInfo(mContext, "内容不能为空！");
			return;
		}
		List<AddImageInfo> list = new ArrayList<AddImageInfo>();
		QianDaoNewWork qiandao = new QianDaoNewWork(mContext, Tools.getNum());
		String typeaa = "汇报记录";
		String relevantName;
		try {
			JsonObject jsonObject = mBeauInfo.recordInformationList.get(0);// 详情对象
			relevantName = typeaa + "【"
					+ GsonUtil.getStringByJson("name", jsonObject) + "】";
			AppContext.relevantName = GsonUtil.getStringByJson("name",
					jsonObject);
		} catch (Exception e) {
			relevantName = typeaa;
			e.printStackTrace();
		}
		qiandao.QiaoDaoChat(null, mEntityId, relevantName, list, name, "1",
				"汇报记录");
		context_text.setText("");
	}

	@Bind(R.id.relevant_bottom)
	LinearLayout relevant_bottom;
	@Bind(R.id.beau_info_edit_web)
	RelativeLayout beau_info_edit_web;

	private String requestKey = "other";

	/*
	 * 切换数据
	 */
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.beau_dynamic:// 动态
			if (mViewPager.getCurrentItem() != 0) {
				mViewPager.setCurrentItem(0);
				setButtomUI(true);
			}
			break;
		case R.id.beau_detail:// 详情
			if (mViewPager.getCurrentItem() != 1) {
				mViewPager.setCurrentItem(1);
				setButtomUI(false);
			}
			break;
		}
	}

	private void setButtomUI(boolean isDynamicFragment) {
		relevant_bottom.setVisibility(isDynamicFragment ? View.VISIBLE
				: View.GONE);
		beau_info_edit_web.setVisibility(isDynamicFragment ? View.GONE
				: View.VISIBLE);
	}

	@Override
	public void onClickLeft(View v) {
		getActivity().finish();
	}

	@Override
	public void onClickRight(View v) {
		showRightPopu(false);
	}

	/**
	 * 显示popu 右边菜单
	 * 
	 * @param isExp
	 *            是展开还是压缩
	 */
	private void showRightPopu(boolean isExp) {
		if (mBeauInfo == null /* || ListUtils.isEmpty(mBeauInfo.relationCreateUrl) */) {
			return;
		}
		if (mRightMenu != null && mRightMenu.isShowing() && isExp) {// 展开
			int popuHeight = 0;
			LinearLayout subContainer = (LinearLayout) mRightMenu
					.getContentView().findViewById(R.id.pop_holder);
			final int count = subContainer.getChildCount();
			for (int i = 0; i < count; i++) {
				View childAt = subContainer.getChildAt(i);
				childAt.setVisibility(i < count - 1 ? View.VISIBLE : View.GONE);
				popuHeight += ViewUtils.getViewMeasuredHeight(childAt);
			}
			mRightMenu.update(AppContext.screenW * 2 / 5,
					Math.min(AppContext.screenH / 2, popuHeight));
		} else {
			PopuWindowUtils.dissmiss(mRightMenu);
			View contentView = (View) View.inflate(mContext,
					R.layout.layout_popu_container, null);
			LinearLayout subContainer = (LinearLayout) contentView
					.findViewById(R.id.pop_holder);
			int popuHeight = 0;
			for (int i = 0; i < ListUtils.getSize(mBeauInfo.relationCreateUrl) + 3; i++) {
				View containerView = View.inflate(mContext,
						R.layout.layout_pop_item, null);
				ImageView ivLogo = (ImageView) containerView
						.findViewById(R.id.pop_item_image);
				ivLogo.setVisibility(View.GONE);
				TextView tvTitle = (TextView) containerView
						.findViewById(R.id.pop_item_text);
				ImageView LIne = (ImageView) containerView
						.findViewById(R.id.item_line);
				if (i < ListUtils.getSize(mBeauInfo.relationCreateUrl)) {
					ivLogo.setImageResource(R.drawable.entity_right_menu);
					ObjMenu objMenu = mBeauInfo.relationCreateUrl.get(i);
					tvTitle.setText(objMenu.relationName);
				} else if (i == ListUtils.getSize(mBeauInfo.relationCreateUrl)) {
					ivLogo.setImageResource(R.drawable.entity_right_menu);
					tvTitle.setText(isMeFollow ? "取消关注" : "关注记录");
				} else if (i == ListUtils.getSize(mBeauInfo.relationCreateUrl) + 1) {
					ivLogo.setImageResource(R.drawable.entity_right_menu);
					tvTitle.setText("删除记录");
				} else if (i == ListUtils.getSize(mBeauInfo.relationCreateUrl) + 2) {
					ivLogo.setImageResource(R.drawable.entity_right_menu);
					tvTitle.setText("更多操作");
				}
				popuHeight += ViewUtils.getViewMeasuredHeight(containerView);
				if (ListUtils.getSize(mBeauInfo.relationCreateUrl) < 4) {
					if (i == ListUtils.getSize(mBeauInfo.relationCreateUrl) + 2) {
						containerView.setVisibility(View.GONE);
					}
				} else {
					if (i > 3 && i != ListUtils.getSize(mBeauInfo.relationCreateUrl) + 2) {
						containerView.setVisibility(View.GONE);
					}
				}
				containerView.setOnClickListener(new MyMenuClick(i));
				subContainer.addView(containerView);
			}
			// 增加上 删除跟加载更多
			mRightMenu = new PopupWindow(contentView,
					AppContext.screenW * 2 / 5,
					ViewGroup.LayoutParams.WRAP_CONTENT);
			mRightMenu.setBackgroundDrawable(new ColorDrawable(
					Color.TRANSPARENT));
			mRightMenu.setFocusable(true);
			mRightMenu.showAsDropDown(headerbar.getRightLayout());
		}

	}

	private class MyMenuClick implements OnClickListener {

		private int mPosition;

		public MyMenuClick(int position) {
			super();
			this.mPosition = position;
		}

		@Override
		public void onClick(View v) {
			if (mPosition < ListUtils.getSize(mBeauInfo.relationCreateUrl)) {
				PopuWindowUtils.dissmiss(mRightMenu);
				ObjMenu objMenu = mBeauInfo.relationCreateUrl.get(mPosition);
				if (StringUtils.equals(objMenu.relationUrl, "www.campaign.com")) {
					JsonObject jsonObject = mBeauInfo.recordInformationList.get(0);// 详情对象
					String name =GsonUtil.getStringByJson("name", jsonObject);
					Intent intent = new Intent(mContext, MarketActivityInfoActivity.class);
					intent.putExtra(ExtraConstant.EXTRA_NAME,name);
					intent.putExtra(ExtraConstant.EXTRA_ID,mEntityId);
					startActivity(intent);
				}else{
					Intent intent = new Intent(mContext, CloudWebViewActivity.class);
					intent.putExtra(
							ExtraConstant.EXTRA_URL,
							UrlManager.getManager().addReturnUrl(
									UrlManager.getManager().getUrlByRoot(
											objMenu.relationUrl)));
					MonitorParam monitorParam = new MonitorParam(new String[] {
							"m=save", "m=query", "type=remark" },
							WebSyncDefaultProxy.STEP_START, new String[] {
									"/WeiXin_index.action", "m=query" }, true,
							WebSyncDefaultProxy.STEP_OVERRIDEURL);
					intent.putExtra("callback", WebSyncDefaultProxy
							.creatDefaultProxy(ReceiverConstant.RECEIVE_REFRESH)
							.addMonitorParam(monitorParam).addHomeMonitor());
					startActivity(intent);
				}
			} else if (mPosition == ListUtils.getSize(mBeauInfo.relationCreateUrl)) {// 跟随或者取消跟随
				PopuWindowUtils.dissmiss(mRightMenu);
				followEntity();
			} else if (mPosition ==ListUtils.getSize(mBeauInfo.relationCreateUrl) + 1) {// 删除
				PopuWindowUtils.dissmiss(mRightMenu);
				deleteEntity();
			} else if (mPosition == ListUtils.getSize(mBeauInfo.relationCreateUrl) + 2) {// 展开更多
				showRightPopu(true);
			}
		}
	};

	@OnClick(R.id.beau_info_edit_web)
	public void clickEdit() {
		Intent intent = new Intent(mContext, CloudWebViewActivity.class);
		MonitorParam monitorParam = new MonitorParam(new String[] { "m=save",
				"m=edit" }, WebSyncDefaultProxy.STEP_START,
				new String[] { "/WeiXin_index.action" }, true,
				WebSyncDefaultProxy.STEP_OVERRIDEURL);
		intent.putExtra(
				"callback",
				WebSyncDefaultProxy
						.creatDefaultProxy(ReceiverConstant.RECEIVE_REFRESH)
						.addMonitorParam(monitorParam).addHomeMonitor());
		if (StringUtils.equalsIgnoreCase(mEntityNameID, "attachement")) {
			intent.putExtra(
					ExtraConstant.EXTRA_URL,
					UrlManager.getManager().addReturnUrl(
							UrlManager.getManager().getEntityDetailEditUrl1(
									mEntityId)));
			startActivity(intent);
		} else {
			intent.putExtra(
					ExtraConstant.EXTRA_URL,
					UrlManager.getManager().addReturnUrl(
							UrlManager.getManager().getEntityDetailEditUrl(
									mEntityId)));
			startActivity(intent);
		}

	}

	private void followEntity() {
		new OtherPresenter().followRecord(mEntityId, isMeFollow,
				new RequestListener() {

					@Override
					public void onSuccess(Object arg0) {
						isMeFollow = !isMeFollow;
						Toast.makeText(mContext,
								isMeFollow ? "关注成功" : "取消关注成功", 0).show();
						RefreshEntiityListEvent event = new RefreshEntiityListEvent();
						event.setOk(true);
						event.setData(new String[] { mEntityId,
								String.valueOf(isMeFollow) });
						EventEngine.post(event);
					}

					@Override
					public void onFailure(ErrorInfo arg0) {
						Toast.makeText(mContext, "操作失败", 0).show();
					}
				});
	}

	private void deleteEntity() {

		if (mBeauInfo == null || ListUtils.isEmpty(mBeauInfo.tabLabel)
				|| mBeauInfo.tabLabel.get(0) == null) {

			Toast.makeText(mContext, "删除失败。。。", 0).show();
			return;
		}
		TabLabel tabLabel = mBeauInfo.tabLabel.get(0);
		mBeauPresenter.deleteEntity(mEntityId, tabLabel.objectapiname,
				new RequestListener() {
					@Override
					public void onSuccess(Object arg0) {
						try {
							Intent intent = new Intent(
									ReceiverConstant.RECEIVE_DELETE);
							mContext.sendBroadcast(intent);
							getActivity().finish();
						} catch (Exception e) {
						}
					}

					@Override
					public void onFailure(ErrorInfo arg0) {
						Toast.makeText(mContext, "删除失败。。。", 0).show();
					}
				});
	}

	private SyncReceiver mSyncReceiver;

	private void initReceiver() {
		mSyncReceiver = new SyncReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ReceiverConstant.RECEIVE_SYNC_WEB);
		filter.addAction(ReceiverConstant.RECEIVE_REFRESH);
		mContext.registerReceiver(mSyncReceiver, filter);
	}

	private class SyncReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			refreshInfoData();
			if (mDetailFragment != null) {
				// refreshInfoData();
				mDetailFragment.refreshWeb();
			}
			if (mDynamicFragment != null) {
				mDynamicFragment.onRefreshData();
			}
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mDynamicFragment.onRefreshData();
		// mDetailFragment.refreshWeb();
		// refreshInfoData();
	}

}
